import 'dart:async';

import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';

/// 枚举音频
enum Audios {
  CallOther,
  Message,
  OnlineVideoCall,
  VideoCall,
}

/// 音频铃声控制类
class Audio {
  Audio() {
    loadAll();
  }

  /// 播放静态资源音频类
  AudioCache _player = AudioCache(prefix: 'audio/');

  /// 音频静态资源
  Map audios = {
    Audios.CallOther: "callOther.mp3",
    Audios.Message: "message.mp3",
    Audios.OnlineVideoCall: "onlineVideoCall.mp3",
    Audios.VideoCall: "videoCall.mp3",
  };

  /// 所有的循环播放音频
  List<AudioPlayer> allLoopAudio = [];

  /// 所有定时的timer
  List allTimer = [];

  /// 销毁
  dispose() {
    stopAllAudio();
    _player.clearCache();
  }

  /// 预先加载所有音频
  Future loadAll() async {
    List<String> fileNames = [];
    audios.forEach((k, v) {
      fileNames.add(v);
    });
    return await _player.loadAll(fileNames);
  }

  /// 播放音频
  Future play(Audios type, {Function callback}) async {
    AudioPlayer player = await _player.play(audios[type]);
    if (callback != null) {
      callback(player);
    }
    return player;
  }

  /// 循环播放
  /// timeClose 定时关闭 默认开启
  /// seconds 定时关闭时间 默认30s
  Future loop(
    Audios type, {
    bool timeClose = true,
    int seconds = 30,
    Function callback,
  }) async {
    AudioPlayer player = await _player.loop(audios[type]);

    allLoopAudio.add(player);

    if (timeClose) {
      allTimer.add(Timer(Duration(seconds: seconds), () {
        stopAllAudio();
        callback();
      }));
    }

    return player;
  }

  /// 停止所有在播放的音频
  void stopAllAudio() {
    print(allLoopAudio);
    allLoopAudio.forEach((item) async{
      print(await item?.stop());
      // item?.stop();
    });
    allLoopAudio.clear();

    allTimer.forEach((item) {
      item?.cancel();
    });
    allTimer.clear();
  }
}
